package com.ruihu.admin.common.async;

import com.ruihu.admin.third.ApplicationContext;
import com.ruihu.admin.util.RhThreadUtil;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class AsyncManager {

    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步定时操作任务调度线程池
     */
    private ScheduledExecutorService executor = ApplicationContext.getBean("scheduledExecutorService", ScheduledExecutorService.class);

    /**
     * 用于IO密集操作的线程池
     */
    private ThreadPoolExecutor threadPoolExecutor4IO = ApplicationContext.getBean("poolExecutorService4IO", ThreadPoolExecutor.class);

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行IO任务
     * @param runnable
     */
    public void executeIOTask(Runnable runnable) {
        this.threadPoolExecutor4IO.execute(runnable);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        RhThreadUtil.shutdownAndAwaitTermination(executor);
    }
}
